import {
    Action,
    createFeatureSelector,
    createReducer,
    createSelector,
    on,
} from '@ngrx/store';
import { AppState } from '../app.model';
import { setUser } from './user.actions';
import { UserState } from './user.model';
function getLocalUser() {
    let user;
    const userStr = localStorage.getItem('user');
    if (userStr) {
        user = JSON.parse(userStr);
    }
    return user;
}
let data: any = getLocalUser();
export const initialState: UserState = {
    username: data ? data.username : undefined,
    token: data ? data.token : undefined,
    auth: data ? data.auth : undefined,
    menus: data ? data.menus : undefined,
};
export const userReducer = createReducer(
    initialState,
    on(setUser, (state, action) => ({
        ...state,
        username: action.user.username,
        token: action.user.token,
        auth: action.user.token,
        menus: action.user.menus,
    }))
);

export const getUserState = createFeatureSelector<AppState,UserState>('user');
export const getUsername = createSelector(
    getUserState,
    (state: UserState) => state.username
);
export const getMenu = createSelector(
    getUserState,
    (state: UserState) => state.menus
);
export const getAuth = createSelector(
    getUserState,
    (state: UserState) => state.auth
);
export const getToken = createSelector(
    getUserState,
    (state: UserState) => state.token
);
